package com.letoken.platform.admin.interceptor;


import cn.hutool.core.util.StrUtil;
import com.letoken.platform.admin.service.AdminMenuService;
import com.letoken.platform.pub.annotation.auth.NotAuthorization;
import com.letoken.platform.pub.annotation.auth.Permission;
import com.letoken.platform.pub.enums.ApiResponseEnum;
import com.letoken.platform.pub.exception.ApiServiceException;
import com.letoken.platform.pub.util.LocalEnvUtils;
import com.letoken.platform.repo.admin.dao.AdminRoleMapper;
import com.letoken.platform.repo.admin.dao.AdminRoleMenuMapper;
import com.letoken.platform.repo.admin.res.system.QueryAdminMenuTreeRes;
import com.letoken.platform.repo.admin.res.user.AdminUserInfoRes;
import com.letoken.platform.repo.app.manager.AppUserSessionManager;
import com.letoken.platform.repo.app.redis.AppLoginTokenRedis;
import com.letoken.platform.repo.utlis.WebUtils;
import jnr.ffi.annotations.In;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * token拦截校验
 *
 * @version 1.0
 * @author： letokenlabs
 * @date： 2021/11/25 16:15
 */
@Log4j2
@Component
public class AdminUserTokenInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private AdminRoleMenuMapper adminRoleMenuMapper;

    @Autowired
    AdminRoleMapper adminRoleMapper;



    /**
     * 前置拦截
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (LocalEnvUtils.isDev() || LocalEnvUtils.isLocal()){
            return true;
        }
      if (handler instanceof HandlerMethod) {
          boolean flag = false;
          HandlerMethod hm = (HandlerMethod) handler;

          Permission permission = hm.getMethodAnnotation(Permission.class);
          if (permission == null) {
              return true;
          }
            //允许swagger的接口不用token
             List<String> swaggerList = Arrays.asList("swaggerResources", "getDocumentation", "error", "errorHtml");
            if (swaggerList.contains(hm.getMethod().getName())) {
                flag = true;
            }
            NotAuthorization notAuthorization = hm.getMethodAnnotation(NotAuthorization.class);
            if (notAuthorization != null) {
                //获取方法中的注解,看是否有该注解 ,如果有，则不需要校验token
                flag = true;
            }

            if (StrUtil.isEmpty(WebUtils.getAuthorization())) {
                throw new ApiServiceException(ApiResponseEnum.ERROR_004);
            }

            if (WebUtils.getAdminUserId() == null) {
                throw new ApiServiceException(ApiResponseEnum.ERROR_004);
            }


          AdminUserInfoRes adminUserInfoRes = AppLoginTokenRedis.me().getAdminUserInfoRes();

          List<String> queryMenuUriList = adminUserInfoRes.getMenuUriList();



            String uri = permission.uri();
            log.info("permission.uri():"+uri);

            String qx = permission.qx();
          log.info("permission.qx():"+qx);

            String rurl= request.getRequestURI();
           log.info("request.getRequestURI():"+rurl);


           flag = queryMenuUriList.stream().anyMatch(name -> qx.equals(name));

              log.info("nameExist:"+flag);



            if (!flag) {
                throw new ApiServiceException(ApiResponseEnum.ERROR_005);
            }

        }
        return true;
    }

}
